package com.ChefApp.mobile;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.Vector;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import android.app.ListActivity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;

public class OpenArchiv extends ListActivity{
	Document receipe;
	String[] fileList;
	Vector<ListItemWithImage> imageItem;
	Element zutatOnly ;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		imageItem = new Vector<ListItemWithImage>();
		File archive = new File(Environment.getExternalStorageDirectory(), "/ChefKochApp/Receipes/");
		fileList = archive.list(new FilenameFilter() {
		    public boolean accept(File d, String name) {
		       return name.endsWith(".xml");
		    }
		});
		
		Toast.makeText(getApplicationContext(), "Es sind "+fileList.length+" Rezepte im Archiv!", Toast.LENGTH_SHORT).show();
		for (String s : fileList) {
			File recFile = new File(Environment.getExternalStorageDirectory(), "/ChefKochApp/Receipes/"+s);
			 StringBuffer contents = new StringBuffer();
		        BufferedReader reader = null;

		        try {
		            reader = new BufferedReader(new FileReader(recFile));
		            String text = null;

		            // repeat until all lines is read
		            while ((text = reader.readLine()) != null) {
		                contents.append(text)
		                    .append(System.getProperty(
		                        "line.separator"));
		            }
		        } catch (FileNotFoundException e) {
		            e.printStackTrace();
		        } catch (IOException e) {
		            e.printStackTrace();
		        } finally {
		            try {
		                if (reader != null) {
		                    reader.close();
		                }
		            } catch (IOException e) {
		                e.printStackTrace();
		            }
		        }
				
				String xml=contents.toString();
				int arrow = xml.indexOf("<");
				xml = xml.substring(arrow);
				receipe = Jsoup.parse(xml);
				Element title =receipe.getElementsByTag("title").first();
				Element subtitle =receipe.getElementsByTag("subtitle").first();
				Element url =receipe.getElementsByTag("url").first();
				Element zutaten =receipe.getElementsByTag("zutatenText").first();
				zutatOnly =receipe.getElementsByTag("zutaten").first();
				Element zubereitung =receipe.getElementsByTag("zubereitung").first();
				Element bewertung = receipe.getElementsByTag("bewertung").first();
				Element userName =receipe.getElementsByTag("uName").first();
				Element portionF =receipe.getElementsByTag("portionen").first();
				Log.v("portion", portionF.text());
				Element brennwert =receipe.getElementsByTag("brennwert").first();
 				Element grad =receipe.getElementsByTag("grad").first();
 				Element zeit =receipe.getElementsByTag("zeit").first();
 				Element datum =receipe.getElementsByTag("datum").first();
 				
 				
 				Zutaten zuClass=new Zutaten(zutatOnly, zutaten.text());
 				String zubereitungStr = zubereitung.text();
				String imageName = s.replace(".xml", ".jpg");
				Bitmap bild = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory()+ "/ChefKochApp/Receipes/"+imageName);
				String bewertungUrl = bewertung.text();
				String titleStr = title.text();
				String uName =userName.text();
				String portion =portionF.text();
 				String brenn = brennwert.text();
 				String gradString = grad.text();
 				String time = zeit.text();
 				String date = datum.text();
 				String recUrl = url.text();
 				String subTitle =subtitle.text();
				imageItem.add( new ListItemWithImage(bild, titleStr, recUrl, subTitle, bewertungUrl,date,gradString,time,brenn,portion,uName,zuClass,zubereitungStr));
			}
	
		ListView lv =getListView(); 
		lv.setBackgroundDrawable(getResources().getDrawable(R.drawable.bluegrad));
		ImageItemAdapter itemAdapter = new ImageItemAdapter(getApplicationContext(), R.layout.image_row, imageItem);
//		setListAdapter(new ArrayAdapter<T>(this, R.layout.resrow, R.id.textViewRes1, (T[]) titles.toArray()));
		setListAdapter(itemAdapter);
	}
	
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		// Get the item that was clicked
		
		@SuppressWarnings("unused")
		Object o = this.getListAdapter().getItem(position);
		
		Intent oaReceipe= new Intent(l.getContext(),OAReceipe.class);
				oaReceipe.putExtra("imageName", imageItem.get(position).getImageUrl());
				oaReceipe.putExtra("title", imageItem.get(position).getTitle());
				oaReceipe.putExtra("zutaten",imageItem.get(position).getZuClass().getText());
				oaReceipe.putExtra("image", imageItem.get(position).getBild());
				oaReceipe.putExtra("zubereitung", imageItem.get(position).getZubereitung());
				oaReceipe.putExtra("portionen", imageItem.get(position).getPortion());
				oaReceipe.putExtra("subtitle", imageItem.get(position).getSubtitle());
				oaReceipe.putExtra("date", imageItem.get(position).getDatum());
				oaReceipe.putExtra("aufwand",imageItem.get(position).getAufwand());
				oaReceipe.putExtra("brenn", imageItem.get(position).getBrenn());
				oaReceipe.putExtra("zutatelement", zutatOnly.text());
				oaReceipe.putExtra("type", imageItem.get(position).getType());
				oaReceipe.putExtra("zeit", imageItem.get(position).getZeit());
				startActivity(oaReceipe);
	}
	
	
}
